﻿using System;
using System.Windows.Forms;
using Report.Entity;
using Report.Service;

namespace Report.Engine
{
    public class ImageAndTableStep : ImageStep
    {
        public ImageAndTableStep(Step step)
            : base(step)
        {
        }

        public override ExecuteResult Execute(ExportContext context)
        {
            HtmlDocument document = context.Document;
            WordProcessor wordProcessor = context.WordProcessor;

            int i;
            for (i = 0; i < int.MaxValue; i++)
            {
                HtmlElement element = document.GetElementById("datatablediv." + i);
                if (element == null) break;
                foreach (HtmlElement child in element.Children)
                {
                    if (!context.FirstDataDone && "cName".Equals(child.GetAttribute("className"), StringComparison.CurrentCultureIgnoreCase))
                    {
                        int index;
                        if (string.IsNullOrEmpty(child.InnerText)) index = -1;
                        else index = child.InnerText.IndexOf(':');
                        wordProcessor.SetTableCell("Data1", i + 3, 1, index > -1 ? child.InnerText.Substring(index + 1) : child.InnerText);
                    }
                    else if ("cResp".Equals(child.GetAttribute("className"), StringComparison.CurrentCultureIgnoreCase))
                    {
                        wordProcessor.SetTableCell("Data1", i + 3, context.FirstDataDone ? 4 : 2, child.InnerText);
                    }
                    else if ("cPct".Equals(child.GetAttribute("className"), StringComparison.CurrentCultureIgnoreCase))
                    {
                        wordProcessor.SetTableCell("Data1", i + 3, context.FirstDataDone ? 5 : 3, child.InnerText);
                    }
                }
            }
            if (context.FirstDataDone)
                wordProcessor.DeleteTableRow("Data1", i + 3);

            context.FirstDataDone = true;

            return base.Execute(context);
        }
    }
}
